﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MotionFramework;
using MotionFramework.Console;
using MotionFramework.Resource;
using MotionFramework.Event;
using MotionFramework.Config;
using MotionFramework.Audio;
using MotionFramework.Network;
using MotionFramework.Scene;
using MotionFramework.Pool;
using MotionFramework.UIKit;
using MotionFramework.Tween;
using YooAsset;
using MotionFramework.HybridCLR;

public class GameLauncher : MonoBehaviour
{
	[Header("运行模式")]
	[SerializeField]
	YooAssets.EPlayMode PlayMode = YooAssets.EPlayMode.EditorSimulateMode;

	[Header("更新地址")]
	[SerializeField]
	string UpdaterServer = "http://127.0.0.1";

	[Header("版本号")]
	[SerializeField]
	string UpdaterVersion = "1";

	void Awake()
	{
// #if !UNITY_EDITOR
// 		PlayMode = YooAssets.EPlayMode.HostPlayMode;
// #endif

		DontDestroyOnLoad(gameObject);

		// 初始化应用
		InitAppliaction();

		// 初始化控制台
		if (Application.isEditor || Debug.isDebugBuild)
			DeveloperConsole.Initialize();

		// 初始化框架
		MotionEngine.Initialize(this, HandleMotionFrameworkLog);
	}

	void Start()
	{
		// 创建游戏模块
		StartCoroutine(CreateGameModules());
	}

	void Update()
	{
		// 更新框架
		MotionEngine.Update();
	}

	void FixedUpdate()
	{
	}

	void OnGUI()
	{
		// 绘制控制台
		if (Application.isEditor || Debug.isDebugBuild)
			DeveloperConsole.Draw();
	}

	/// <summary>
	/// 初始化应用
	/// </summary>
	private void InitAppliaction()
	{
		Application.runInBackground = true;
		Application.backgroundLoadingPriority = ThreadPriority.High;

		// 设置最大帧数
		Application.targetFrameRate = 60;

		// 屏幕不休眠
		Screen.sleepTimeout = SleepTimeout.NeverSleep;
	}

	/// <summary>
	/// 监听框架日志
	/// </summary>
	private void HandleMotionFrameworkLog(ELogLevel logLevel, string log)
	{
		if (logLevel == ELogLevel.Log)
		{
			UnityEngine.Debug.Log(log);
		}
		else if (logLevel == ELogLevel.Error)
		{
			UnityEngine.Debug.LogError(log);
		}
		else if (logLevel == ELogLevel.Warning)
		{
			UnityEngine.Debug.LogWarning(log);
		}
		else if (logLevel == ELogLevel.Exception)
		{
			UnityEngine.Debug.LogError(log);
		}
		else
		{
			throw new NotImplementedException($"{logLevel}");
		}
	}

	private string GetUpdaterServer()
	{
#if UNITY_EDITOR
		if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android)
			return $"{UpdaterServer}/Android/{UpdaterVersion}";
		else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS)
			return $"{UpdaterServer}/IPhone/{UpdaterVersion}";
		else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL)
			return $"{UpdaterServer}/WebGL/{UpdaterVersion}";
		else
			return $"{UpdaterServer}/StandaloneWindows64/{UpdaterVersion}";
#else
		if (Application.platform == RuntimePlatform.Android)
			return $"{UpdaterServer}/Android/{UpdaterVersion}";
		else if (Application.platform == RuntimePlatform.IPhonePlayer)
			return $"{UpdaterServer}/IPhone/{UpdaterVersion}";
		else if (Application.platform == RuntimePlatform.WebGLPlayer)
			return $"{UpdaterServer}/WebGL/{UpdaterVersion}";
		else
			return $"{UpdaterServer}/StandaloneWindows64/{UpdaterVersion}";
#endif
	}

	/// <summary>
	/// 创建游戏模块
	/// </summary>
	private IEnumerator CreateGameModules()
	{
		// 创建事件管理器
		MotionEngine.CreateModule<EventManager>();

		// 创建补间管理器
		MotionEngine.CreateModule<TweenManager>();

		// 创建资源管理器
		if(PlayMode == YooAssets.EPlayMode.EditorSimulateMode)
		{
			var resourceCreateParam = new YooAssets.EditorSimulateModeParameters();
			resourceCreateParam.LocationServices = new DefaultLocationServices("Assets/ResourcesHot");
			MotionEngine.CreateModule<ResourceManager>(resourceCreateParam);
			var operation = ResourceManager.Instance.InitializeAsync();
			yield return operation;
		}
		else if(PlayMode == YooAssets.EPlayMode.OfflinePlayMode)
		{
			var resourceCreateParam = new YooAssets.OfflinePlayModeParameters();
			resourceCreateParam.LocationServices = new DefaultLocationServices("Assets/ResourcesHot");
			MotionEngine.CreateModule<ResourceManager>(resourceCreateParam);
			var operation = ResourceManager.Instance.InitializeAsync();
			yield return operation;
		}
		else
		{
			var resourceCreateParam = new YooAssets.HostPlayModeParameters();
			resourceCreateParam.LocationServices = new DefaultLocationServices("Assets/ResourcesHot");
			resourceCreateParam.DecryptionServices = null;
			resourceCreateParam.ClearCacheWhenDirty = false;
			resourceCreateParam.DefaultHostServer = GetUpdaterServer();
			resourceCreateParam.FallbackHostServer = GetUpdaterServer();
			resourceCreateParam.VerifyLevel = EVerifyLevel.High;
			MotionEngine.CreateModule<ResourceManager>(resourceCreateParam);
			var operation = ResourceManager.Instance.InitializeAsync();
			Debug.Log(GetUpdaterServer());
			yield return operation;
		}

		// 创建对象池管理器
		var poolCreateParam = new GameObjectPoolManager.CreateParameters();
		poolCreateParam.DefaultDestroyTime = 5f;
		MotionEngine.CreateModule<GameObjectPoolManager>(poolCreateParam);

		// 创建音频管理器
		MotionEngine.CreateModule<AudioManager>();

		// 创建配置表管理器
		MotionEngine.CreateModule<ConfigManager>();

		// 创建场景管理器
		MotionEngine.CreateModule<SceneManager>();

		// 创建窗口管理器
		MotionEngine.CreateModule<WindowManager>();

		// 创建热更新管理器
		MotionEngine.CreateModule<HotfixManager>();

		// 注册反射服务接口
		//ConfigManager.Instance.ActivatorServices = ILRManager.Instance;

		// 开始游戏
		(GameFacade.Instance as GameFacade).Launcher();
	}
}